const app = getApp();

Page({
  data: {
    phone:'',
    code:'',
    isCode:true,
    codeTime:120,
    codeName:'120s后获取',
  },
  onLoad(r){
    
  },
  blurPhone(e){
    this.setData({
      phone:e.detail.value
    });
  },
  onShareAppMessage() {
    return {
      title: '花礼鲜花玫瑰生日',
      desc: '花礼鲜花玫瑰生日',
      path: 'pages/todos/todos'
    };
  },
  blurCode(e){
    this.setData({
      code:e.detail.value
    });
  },
  monitorData(){
    var that = this;
    var codeTime = that.data.codeTime;
    if(codeTime<1){
      that.setData({
        isCode:true
      });
    }else{
      that.setData({
        codeTime:(codeTime-1),
        codeName:codeTime+'s后获取'
      })
    }
  },
  getCode(){
    var that = this;
    var phone = that.data.phone;
    if(!phone){
      my.alert({content: '请输入手机号码'});
      return;
    }
    my.getStorage({
      key: 'token',
      success: function(res) {   
        my.httpRequest({
          url: app.geturl+'/sms/bind-mobile',
          method: 'GET',
          data: {
            token: res.data.token,
            mobile:phone
          },
          dataType: 'json',
          success: function(re) {
            if(re.data.code==0){
              that.setData({
                isCode:false
              });
              setInterval(that.monitorData.bind(that),1000);
            }else{
              my.alert({content: re.data.msg});
              return;
            }
          }
        });
      }
    });
    
  },
  subCode(){
    var that = this;
    var phone = that.data.phone;
    if(!phone){
      my.alert({content: '请输入手机号码'});
      return;
    }
    var code = that.data.code;
    if(!code){
      my.alert({content: '请输入验证码'});
      return;
    }
    my.getStorage({
      key: 'token',
      success: function(res) {   
        my.httpRequest({
          url: app.geturl+'/member/bind-mobile?token='+res.data.token,
          method: 'POST',
          data: {
            mobile:phone,
            verify_code:code
          },
          dataType: 'json',
          success: function(re) {
            if(re.data.code==0){
              if(re.data.msg=='绑定成功'){
                my.navigateBack({
                  delta:1
                })
              }else{
                my.alert({content:re.data.msg});
                return;
              }
            }else if(re.data.msg=='请登录后重试'){
              app.memberLogin();
            }else{
               my.alert({content:re.data.msg});
               return;
            }
          }
        });
      }
    });
  },
  cancleCode(){
    my.navigateBack({
      delta:1
    })
  },
});
